<template>
  <div class="global-container">
    <div class="global-header">
      <el-image
        style="width: 100px; height: 100px"
        :src="require('@/assets/header_images/current.png')"
      ></el-image>
      <div class="title">
        镜像管理
        <div class="title-content">
          提供系统Docker的集中管理能力，支持镜像导出、导出等能力。
        </div>
      </div>
    </div>
    <div class="searchDiv1">
      <div class="searchDiv global-operate">
        <span class="keyword">关键词：</span>
        <el-input
          v-model="searchInput"
          placeholder="请输入名称进行检索"
          clearable
          class="inputStyle"
          style="width: 20%"
          prefix-icon="el-icon-search"
          @input="filterImageList"
        />
        <div class="right-menu">
          <el-button
            style="width: 100px"
            type="primary"
            @click="uploadDialogVisible = true"
            class="el-button-primary-style"
          >
            导入
          </el-button>
        </div>
      </div>
    </div>
    <div class="servicePackageList">
      <div>
        <el-table
          ref="multipleTable"
          :data="tableData"
          :cell-style="{ textAlign: 'left', paddingLeft: '30px' }"
          :header-cell-style="{ textAlign: 'left', paddingLeft: '30px' }"
          height="60vh"
        >
          <!--          @selection-change="tableSelectionChange"-->
          <!--          <el-table-column type="selection"/>-->
          <el-table-column prop="imageName" label="名称" width="300">
            <template slot-scope="scope">
              <div class="ellipsis">
                {{ scope.row.imageName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="imageVersion" label="版本" width="100"/>
          <el-table-column prop="imageDescription" label="描述" width="300"/>
          <el-table-column prop="imageCompany" label="类别">
            <template slot-scope="scope">
            <p>
              {{ getImageType(scope.row.imageType) }}
            </p>
          </template>
          </el-table-column>
          <el-table-column prop="imageCompany" label="单位"/>
          <el-table-column prop="createBy" label="上传用户" width="150"/>
          <el-table-column prop="updateTime" label="创建时间" width="250"/>
          <el-table-column label="操作" width="250">
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="downloadImage(scope.row)"
                style="margin-right: 10px; padding: 0"
              >
                下载
              </el-button>
              <el-button
                type="text"
                @click="reloadImage(scope.row)"
                style="margin-right: 10px; padding: 0"
              >
                重传
              </el-button>
              <el-popconfirm
                title="确定删除此镜像信息吗？"
                @confirm="deleteImageByRowId(scope.row)"
              >
                <el-button
                  slot="reference"
                  type="text"
                  style="color: #f56c6c; padding: 0"
                >
                  删除
                </el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style="margin-top: 10px; float: right">
        <el-pagination
          background
          layout="total, prev, pager, next, jumper"
          :total="page.total"
          :page-size="page.pageSize"
          :page.sync="page"
          @current-change="changePage"
        />
      </div>
    </div>
    <div>
      <el-dialog
        title="导入镜像包"
        :visible.sync="uploadDialogVisible"
        width="30%"
        :before-close="beforeCloseUploadDialog"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
      >
        <div>
          <el-form
            ref="form"
            :model="GvStoreImageConfirmVo"
            :rules="GvStoreImageConfirmVoRules"
            label-width="80px"
          >
          <el-form-item label="镜像单位" prop="imageCompany">
              <el-input
                v-model="GvStoreImageConfirmVo.imageCompany"
                placeholder="请先填写镜像单位"
              ></el-input>
            </el-form-item>
            <el-form-item label="镜像描述" prop="imageDescription">
              <el-input
                v-model="GvStoreImageConfirmVo.imageDescription"
                placeholder="请先填写镜像描述，再进行文件上传"
              ></el-input>
            </el-form-item>
          </el-form>
          <el-upload
            class="uploadDiv"
            :action="uploadPath"
            :before-upload="beforeUpload"
            :before-remove="beforeRemove"
            :limit="1"
            :file-list="fileList"
            accept=".tar"
            :on-success="onUploadSuccess"
            :on-error="onUploadError"
            :disabled="
              fileList.length === 1 ||
              GvStoreImageConfirmVo.imageDescription === ''
              || GvStoreImageConfirmVo.imageCompany === ''
            "
            :destroy-on-close="true"
          >
            <el-button
              size="small"
              type="primary"
              class="el-button-primary-style"
            >
              点击上传
            </el-button>
            <div slot="tip" class="el-upload__tip">
              文件格式：.tar，单个文件不能超过2048MB
            </div>
          </el-upload>
        </div>
        <div style="margin-top: 15px">
          <h2>日志信息</h2>
          <div class="logDetailsDiv">
            <div v-for="(msg, index) in msgArray" :key="index">
              {{ msg }}
            </div>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button
            type="primary"
            size="small"
            @click="closeUploadDialog"
            class="el-button-primary-style"
          >
            关 闭
          </el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import * as uuid from "uuid";
  import {Subject} from "rxjs";

  export default {
    name: "ImageManage.vue",
    data() {
      return {
        searchInput: "",
        tableData: [],
        selectImageList: [],
        uploadDialogVisible: false,
        fileList: [],
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0,
        },
        tmpPage: {
          pageSize: 10,
          pageNum: 1,
          filterKey: "",
        },
        baseUploadPath: "/appstore/imageinfo/upload/",
        uploadPath: "/appstore/imageinfo/upload/",
        topic: "",
        msgArray: [],
        GvStoreImageConfirmVo: {
          route: "", // 上传路径
          imageAlreadyExists: [], // 镜像已存在列表
          imageNameConflict: [], // 镜像名冲突列表
          imageName: "", // 镜像名称
          imageVersion: "", // 镜像版本
          imageDescription: "", // 镜像描述
          imageCompany: "", // 镜像单位
        },
        GvStoreImageConfirmVoRules: {
          imageDescription: [
            {
              required: true,
              message: "请填写镜像描述",
              trigger: ["blur", "change"],
            },
          ],
          imageCompany: [
            {
              required: true,
              message: "请填写镜像单位",
              trigger: ["blur", "change"],
            },
          ],
        },
      };
    },
    beforeMount() {
      this.getAllImageByPage();
      this.topic = uuid.v4();
      this.uploadPath = this.baseUploadPath + this.topic;
    },
    methods: {
      getImageType(operateTarget) {
      const statusMap = {
        0: "外部镜像",
        1: "服务包",
        2: "中间件上传",
      };
      return statusMap[operateTarget] || "未知类型";
    },
      // 分页获取所有镜像信息
      getAllImageByPage() {
        this.$imageManageApi
          .getImageInfoListByPage(this.tmpPage)
          .then((res) => {
            if (res && res.code === 200) {
              this.tableData = res.data.records;
              this.page.total = res.data.total;
            }
          })
          .catch((error) => {
            this.$message.error(error.message);
          });
      },
      // 过滤展示
      filterImageList() {
        this.tmpPage.filterKey = this.searchInput;
        this.tmpPage.pageNum = 1;
        this.tmpPage.pageSize = 10;
        this.getAllImageByPage();
      },
      // 更换页数
      changePage(currentPage) {
        this.page.currentPage = currentPage;
        this.tmpPage.pageNum = currentPage;
        this.getAllImageByPage();
      },
      // 处理更多
      // tableSelectionChange(selectList) {
      //   this.selectImageList = selectList
      // },
      //处理操作命令
      deleteImageByRowId(row) {
        this.$imageManageApi
          .deleteImages([row.id])
          .then((res) => {
            if (res && res.code === 200) {
              this.$message.success(res.data);
              this.getAllImageByPage();
            }
          })
          .catch((error) => {
            this.$message.error(error.message);
          });
      },
      downloadImage(row) {
        window.open(`/appstore/imageinfo/download/?ids=${row.id}`);
      },
      reloadImage(row) {
        this.$imageManageApi
          .reloadImages([row.id])
          .then((res) => {
            if (res && res.code === 200) {
              this.$message.success(res.data);
            }
          })
          .catch((error) => {
            this.$message.error(error.message);
          });
      },
      beforeCloseUploadDialog(done) {
        if (
          this.msgArray.length === 0 ||
          !this.msgArray[0].includes("upload_end")
        ) {
          this.$confirm("任务尚未完成，确认关闭？")
            .then((_) => {
              this.fileList = [];
              this.getAllImageByPage();
              done();
            })
            .catch((_) => {
            });
        } else {
          this.getAllImageByPage();
          this.fileList = [];
          done();
        }
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`);
      },
      closeUploadDialog() {
        if (
          this.msgArray.length === 0 ||
          !this.msgArray[0].includes("upload_end")
        ) {
          this.$confirm("任务尚未完成，确认关闭？")
            .then((_) => {
              this.closeInfoOperate();
            })
            .catch((_) => {
            });
        } else {
          this.closeInfoOperate();
        }
      },
      closeInfoOperate() {
        this.getAllImageByPage();
        this.fileList = [];
        this.msgArray = [];
        this.uploadDialogVisible = false;
        this.GvStoreImageConfirmVo.imageDescription = "";
        this.GvStoreImageConfirmVo.imageCompany = "";
      },
      beforeUpload(file) {
        const isLt2G = file.size / 1024 / 1024 < 2048;
        if (!isLt2G) {
          this.$message.error("上传文件大小不能超过 2048MB!");
        }
        this.openMessage();
        return isLt2G;
      },
      onUploadSuccess(res) {
        if (res.code === 200) {
          let param = {
            topic: this.topic,
            route: res.data,
          };
          this.GvStoreImageConfirmVo.route = res.data;
          this.$imageManageApi
            .analysisImagesTar(param)
            .then((res1) => {
              if (res1 && res1.code === 200) {
                let par = {
                  topic: this.topic,
                  GvStoreImageConfirmVo: this.GvStoreImageConfirmVo,
                };
                if (
                  res1.data.imageAlreadyExists.length === 0 &&
                  res1.data.imageNameConflict.length === 0
                ) {
                  this.$imageManageApi.confirmImagesTar(par).then((response) => {
                    if (response && response.code === 200) {
                      this.$message.success("镜像包上传成功");
                    }
                  });
                } else if (
                  res1.data.imageAlreadyExists.length !== 0 ||
                  res1.data.imageNameConflict.length !== 0
                ) {
                  this.GvStoreImageConfirmVo.imageAlreadyExists =
                    res1.data.imageAlreadyExists;
                  this.GvStoreImageConfirmVo.imageNameConflict =
                    res1.data.imageNameConflict;
                  let imageAlreadyExists = "";
                  res1.data.imageAlreadyExists.forEach((ele) => {
                    imageAlreadyExists += ele + ",";
                  });
                  this.$confirm(
                    `镜像${imageAlreadyExists.substring(
                      0,
                      imageAlreadyExists.length - 1
                    )}已存在，是否进行覆盖上传？`,
                    "上传确认",
                    {
                      confirmButtonText: "确定",
                      cancelButtonText: "取消",
                      type: "warning",
                    }
                  )
                    .then(() => {
                      this.$imageManageApi
                        .confirmImagesTar(par)
                        .then((response) => {
                          if (response && response.code === 200) {
                            this.$message.success("镜像包上传成功");
                            this.closeUploadDialog();
                          }
                        });
                    })
                    .catch(() => {
                      this.$imageManageApi
                        .cancelImagesTar(param)
                        .then((response) => {
                          if (response && response.code === 200) {
                            this.$message.success("镜像包取消上传");
                            this.closeUploadDialog();
                          }
                        });
                    });
                }
              }
            })
            .catch((error) => {
              this.$message.error(error.message);
            });
        } else {
          this.$message.error("文件上传失败：" + res.msg);
          this.fileList = [];
        }
      },
      onUploadError(error) {
        this.$message.error("文件上传失败：" + error);
      },
      openMessage() {
        this.msgArray = [];
        let subs = new Subject();
        let eventSource = new EventSource(`/appstore/webflux/sse/${this.topic}`);
        let first = true;
        eventSource.onmessage = (e) => {
          if (!first) {
            subs.next(e.data);
          } else {
            first = false;
          }
        };
        eventSource.onerror = (e) => {
          eventSource.close();
        };
        subs.subscribe((msg) => {
          this.msgArray.unshift(msg);
        });
      },
    },
  };
</script>

<style lang="css" scoped>
  .uploadDiv {
    height: 100px;
  }

  .ellipsis {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .ellipsis:hover {
    overflow: visible;
  }

  .logDetailsDiv {
    border: 1px solid #ededed;
    height: 150px;
    overflow-y: scroll;
  }

  /*.el-button {*/
  /*  border-radius: 30px;*/
  /*  display: inline-block;*/
  /*  margin: 0 8px;*/
  /*}*/

  /*::v-deep .el-button--primary {*/
  /*  background-color: #304156;*/
  /*  border-color: #304156;*/
  /*}*/

  ::v-deep .el-pagination.is-background .el-pager li:not(.disabled).active {
    background-color: #304156;
  }
</style>
